package com.google.unizone.server;

import java.util.List;

import javax.jdo.PersistenceManager;

import com.google.appengine.api.datastore.Transaction;


public class DBSimpleLogic {

	public static void createStudent(TestStudet student) {
		if (student != null) {
			storeToDB(student);
		} else {
			System.out.println("ERROR : (DB_Logic) Attempt to create empty student");
		}
	}
	
	
	
	public static void storeToDB(Object object) {
			PersistenceManager pm = PMF.get().getPersistenceManager();

		try {
			Object o=pm.makePersistent(object);
			o.toString();
			//System.out.println(((TestStudet)object).getKey().getId());
			//System.out.println(((TestStudet)o).getKey().getId());
		} catch(Exception e) {
			if (pm == null) {
				System.out.println("HERE");
			} else {
				System.out.println(pm.toString());
			}
			System.out.println("storeToDB ERROR"+e.getMessage() + e.getClass().toString());
		} finally {
			pm.close();
		}
	}
	
	public static void updateCourse(TestStudet course){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		javax.jdo.Transaction tx = pm.currentTransaction();
		try
		{
		    tx.begin();
		    TestStudet updatedCourse = pm.getObjectById(TestStudet.class, course.getID());
			
		    updatedCourse.setCourseName(course.getCourseName());
		    updatedCourse.setSemester(course.getSemester());
		    //updatedCourse.setLessonTimes(course.getLessonTimes());
		    updatedCourse.setStudentIDList(course.getStudentIDList());
		    updatedCourse.setMoedADate(course.getMoedADate());
		    updatedCourse.setMoedBDate(course.getMoedBDate());
		    
		    pm.makePersistent(updatedCourse);
		    tx.commit();
		}
		catch (Exception e)
		{
			System.out.println("ERROR : (DB_Logic - updateCourse) **** " + e.getMessage());
		    if (tx.isActive())
		    {
		        tx.rollback();
		    }
		}
		finally
		{
			pm.close();
		}
	}
	
	public static void updateStudent(Student student){
		PersistenceManager pm = PMF.get().getPersistenceManager();
		javax.jdo.Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			Student updatedStudent = pm.getObjectById(Student.class, student.getFacebookID());
			updatedStudent.setName(student.getName());
			updatedStudent.setAccessToken(student.getAccessToken());
			updatedStudent.setFaculty(student.getFaculty());
			updatedStudent.setPic(student.getPic());
			updatedStudent.setFBFriends(student.getFBFriends());
			updatedStudent.setCourseIDList(student.getCourseIDList());
			updatedStudent.setYear(student.getYear());
			pm.makePersistent(updatedStudent);
			tx.commit();
		} catch (Exception e) {
			System.out.println("ERROR : (DB_Logic - updateStudent) **** " + e.getMessage());
			if (tx.isActive()) {
				tx.rollback();
			}
		} finally {
			pm.close();
		}
	}
	
	public static void removeStudent(Student student) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
        try {
            pm.currentTransaction().begin();
            student = pm.getObjectById(Student.class, student.getFacebookID());
            pm.deletePersistent(student);
            pm.currentTransaction().commit();
        } catch (Exception ex) {
            pm.currentTransaction().rollback();
            throw new RuntimeException(ex);
        } finally {
            pm.close();
        }
	}	
	
	
	
	public static void removeCourse(TestStudet course) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.currentTransaction().begin();
			// We don't have a reference to the selected Product.
			// So we have to look it up first, 
			course = pm.getObjectById(TestStudet.class, course.getID());
			pm.deletePersistent(course);
			pm.currentTransaction().commit();
			} catch (Exception ex) {
				pm.currentTransaction().rollback();
				throw new RuntimeException(ex);
		} finally {
				pm.close();
		} 
	}
	
	public static TestStudet getCourse(String id) {      
        PersistenceManager pm = PMF.get().getPersistenceManager();
        //List<Customer> customer = new LinkedList<Customer>();  
        TestStudet s = null;
        String query= "select from " + TestStudet.class.getName() + " where courseID == '" + id +"'";
        
        try{
                @SuppressWarnings("unchecked")
                List<TestStudet> student = (List<TestStudet>) pm.newQuery(query).execute();
                if (student.size() > 0){
                        s = student.get(0);
                }
                //System.out.println("DEBUG *******" + s.getLessonTimes());
        }
        finally{
                pm.close();
        }
        return s;
	}
	
	public static TestStudet getStudent(String id) {      
        PersistenceManager pm = PMF.get().getPersistenceManager();
        //List<Customer> customer = new LinkedList<Customer>();  
        TestStudet s = null;
        String query= "select from " + TestStudet.class.getName() + " where facebookID == '" + id +"'";
        
        try{
                @SuppressWarnings("unchecked")
                List<TestStudet> student = (List<TestStudet>) pm.newQuery(query).execute();
                if (student.size() > 0){
                        s = student.get(0);
                }
        }
        finally{
                pm.close();
        }
        return s;
	}
	
	public static Lesson getLesson(String id) {      
        PersistenceManager pm = PMF.get().getPersistenceManager();
        //List<Customer> customer = new LinkedList<Customer>();  
        Lesson s = null;
        String query= "select from " + Lesson.class.getName() + " where lessDay == '" + id +"'";
        try{
                @SuppressWarnings("unchecked")
                List<Lesson> student = (List<Lesson>) pm.newQuery(query).execute();
                if (student.size() > 0){
                        s = student.get(0);
                }
        }
        finally{
                pm.close();
        }
        return s;
	}
	
	public static Boolean checkIfStudentExist(String id) {
        PersistenceManager pm = PMF.get().getPersistenceManager();
        //List<Customer> customer = new LinkedList<Customer>();
        String query= "select from " + TestStudet.class.getName() + " where courseID == '" + id +"'";
        try{
                @SuppressWarnings("unchecked")
                List<TestStudet> student = (List<TestStudet>) pm.newQuery(query).execute();
                if (student.size() > 0){
                        return true;
                }
        }
        finally{
                pm.close();
        }
        return false;
    }
}
